<template>
    <div class="p-2 addListBox">
      <div v-if="route.query.type == 'add'" style="margin: 20px 10px;font-weight: 600;font-size: 26px;display:flex;align-items: center;">添加车库物业费缴费记录</div>
      <div v-else style="margin: 20px 10px;font-weight: 600;font-size: 26px;display:flex;align-items: center;">修改车库物业费缴费记录</div>
      <el-card shadow="never">
        <el-table v-loading="loading" :data="assetCatalogList">
          <el-table-column align="center">
            <template #header>
              <div>小区名称 <span style="color: #ff0000;">*</span></div>
              <!-- <el-switch
                v-model="xmswitchType"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="整体一致"
                inactive-text="逐个修改"
                disabled
              /> -->
            </template>
            <template #default="scope">
                <el-select
                    class="slese"
                    @visible-change="xmhandleVisibleChange"
                    v-model="scope.row.projectId"
                    placeholder="请选择项目"
                    ref="selectRef"
                    @change="xmchanged($event,scope.row)"
                    v-if="route.query.type == 'add'"
                >
                    <el-option class="xmDropdown" v-for="item in xmOptions" :key="item.id" :label="item.projectName" :value="item.id" />
                    <p class="el-select-dropdown__empty" v-show="loadingmore">加载中</p>
                </el-select>
                <span v-else> {{scope.row.projectName}} </span>
            </template>
          </el-table-column>

          <el-table-column align="center">
            <template #header>
              <div>房屋号 <span style="color: #ff0000;">*</span></div>
            </template>
            <template #default="scope">
            <el-select
              class="slese"
              @visible-change="househandleCkVisibleChange($event,scope)"
              v-model="scope.row.houseId"
              placeholder="请选择房屋"
              ref="selectRef"
              filterable
              v-if="route.query.type == 'add'"
              :filter-method="getHouseHomeList"
            >
              <el-option
                class="housCKAddDropdown"
                v-for="item in houseCostList"
                :key="item.houseId"
                :label="item.houseNumber"
                :value="item.houseId"
              />
              <p class="el-select-dropdown__empty" v-show="loadingHouseMore">加载中</p>
            </el-select>
            <el-input v-else v-model="scope.row.houseNumber" placeholder="请输入房屋号" disabled />
          </template>
          </el-table-column>
  
          <el-table-column align="center">
            <template #header>
              <div>车库号 <span style="color: #ff0000;">*</span></div>
            </template>
            <template #default="scope">
                <el-input maxlength="60" v-model="scope.row.bicycleNumber" placeholder="请输入车库号" />
            </template>
          </el-table-column>
          <el-table-column align="center">
            <template #header>
              <div>车库面积 <span style="color: #ff0000;">*</span></div>
              <!-- <el-switch
                  v-model="ckAreaSwitchType"
                  class="ml-2"
                  inline-prompt
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  active-text="整体一致"
                  inactive-text="逐个修改"
                /> -->
            </template>
            <template #default="scope">
                <el-input type="number" v-model="scope.row.bicycleArea" placeholder="请输入车库号" @input="countWYF($event,scope.row)" />
            </template>
          </el-table-column>
          <!-- <el-table-column align="center">
            <template #header>
              <div>车库物业费/㎡ 单价 <span style="color: #ff0000;">*</span></div>
              <el-switch
                v-model="SKWYFSwitchType"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="整体一致"
                inactive-text="逐个修改"
                disabled
            />
            </template>
            <template #default="scope">
                <el-input v-model="scope.row.CKWYF" placeholder="请输入车库物业费/㎡ 单价" disabled @change="changeBicyCost($event,scope.row)" />
            </template>
          </el-table-column> -->
          <el-table-column align="center" width="400">
            <template #header>
              <div>车库物业费 <span style="color: #ff0000;">*</span></div>
              <!-- <el-switch
                  v-model="bicyCostSwitchType"
                  class="ml-2"
                  inline-prompt
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  active-text="整体一致"
                  inactive-text="逐个修改"
                /> -->
            </template>
            <template #default="scope">
              <div style="display: flex;justify-content:left;width:100%;">
                <el-input
                  type="number"
                  v-model="scope.row.CKWYF"
                  placeholder="单价"
                  style="width: 130px"
                  @input="changeBicyCost($event,scope.row)"
                />
                <div style="margin:0 10px;">×</div>
                <el-input v-model="scope.row.bicycleArea" disabled style="width: 100px" />
                <div style="margin:0 10px;">=</div>
                <el-input
                  type="number"
                  v-model="scope.row.bicycleManagementCost"
                  placeholder="车库物业费"
                  style="width: 130px"
                  @input="countWYFDJ($event,scope.row)"
                />
              </div>
                <!-- <el-input type="number" v-model="scope.row.bicycleManagementCost" @input="countWYFDJ($event,scope.row)" placeholder="请输入车库物业费" /> -->
            </template>
          </el-table-column>
          <el-table-column align="center">
            <template #header>
              <div>
                <div>是否开具发票</div>
                <el-switch
                  v-model="isNeedInvoiceType"
                  class="ml-2"
                  inline-prompt
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  active-text="整体一致"
                  inactive-text="逐个修改"
                />
              </div>
            </template>
            <template #default="scope">
              <el-select
              class="slese"
              v-model="scope.row.isNeedInvoice"
              placeholder="请选择"
              ref="selectRef"
              @change="isNeedInvoiceChanged($event,scope.row)"
            >
              <el-option v-for="item in is_need_invoice" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" width="300px">
            <template #header>
              <div>
                <div>车库物业费周期 <span style="color: #ff0000;">*</span></div>
                <el-switch
                  v-model="timeRangeSwitchType"
                  class="ml-2"
                  inline-prompt
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  active-text="整体一致"
                  inactive-text="逐个修改"
                />
              </div>
            </template>
            <template #default="scope">
                <el-date-picker
                    v-model="scope.row.bicycleManagementStartDate"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="选择开始日期"
                    @change="startTimer($event,scope.row)"
                ></el-date-picker>
                <span style="margin:0 6px">至</span>
                <el-date-picker
                    v-model="scope.row.bicycleManagementEndDate"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="选择结束日期"
                    @change="endTimer($event,scope.row)"
                ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column v-if="routeType == 'add'" label="操作" align="center" class-name="small-padding fixed-width" width="50px">
            <template #default="scope">
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="assetCatalogList = assetCatalogList.filter(item => item != scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <div style="display: flex;justify-content: center;margin-top: 20px;">
        <el-button v-if="route.query.type == 'add'" type="primary" icon="Plus" @click="addLine">追加一条</el-button>
        <el-button v-if="route.query.type == 'add'" type="success" icon="Position" @click="handleQuery">提交全部</el-button>
        <el-button v-else type="success" icon="Position" @click="handleQuery">提交修改</el-button>
        <el-button @click="goBack">返 回</el-button>
      </div>
    </div>
  </template>
  
<script setup name="AssetCataAdd" lang="ts">
import { listBicycleCost, getBicycleCost, delBicycleCost, addBicycleCost, updateBicycleCost } from '@/api/business/garageCost';
import { listHouseInfo } from '@/api/business/houseInfo';
import { ProjectQuery } from '@/api/business/project/types';
import { listProject } from '@/api/business/project';
import { HouseCostVO } from '@/api/business/houseCost/types';
import { ref } from 'vue'
import { listStandard } from '@/api/business/standard';
import { addDays } from 'date-fns';
import router from '@/router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { charge_category ,is_need_invoice } = toRefs<any>(proxy?.useDict('charge_category','is_need_invoice'));
const route = useRoute()

const routeType = ref('add');
const loading = ref(true);
const assetCatalogList = ref([]);
// const xmswitchType = ref(true);
// const ckAreaSwitchType = ref(true);
// const SKWYFSwitchType = ref(true);
// const bicyCostSwitchType = ref(true);
const isNeedInvoiceType = ref(true);
const timeRangeSwitchType = ref(true);
const xmOptions = ref()
const xmtotal = ref(0);
const xmqueryParams = ref<ProjectQuery>({
    pageNum: 1,
    pageSize: 10,
    isExit: 0
})
const loadingmore = ref(false)
const houseCostList = ref<HouseCostVO[]>([]);
const CKtotal = ref(0)
const queryParamsFW = ref({
  pageNum: 1,
  pageSize: 10,
  projectId: undefined,
  houseNumber:undefined,
});
const loadingHouseMore = ref(false)
const listItem = {
    projectId:'',
    houseId:'',
    bicycleNumber: '',
    bicycleArea: '',
    CKWYF: '',
    bicycleManagementCost: '',
    bicycleManagementStartDate: '',
    bicycleManagementEndDate: '',
    isNeedInvoice:'0'
}
const queryParamsSF = ref({
  pageNum: 1,
  pageSize: 10,
  chargeCategory: undefined
});
const scopeCkHouseIndex=ref(0)
const ckwyfValue=ref(0)
const errRowIndexList=ref([])
  
/** 查询项目管理列表 */
const getList = async () => {
    loading.value = true;
    const xm = await listProject(xmqueryParams.value);
    xmOptions.value = xm.rows
    xmtotal.value = xm.total;
    queryParamsSF.value.chargeCategory = charge_category.value[5].value
    const res = await listStandard(queryParamsSF.value);
    listItem.CKWYF = res.rows[0].chargeMoney
    ckwyfValue.value = res.rows[0].chargeMoney
    loading.value = false;
}

  // 追加一条
const addLine = () => {
    if(assetCatalogList.value.length > 0) {
        // xmswitchType.value?listItem.projectId=assetCatalogList.value[0].projectId:''
        // ckAreaSwitchType.value?listItem.bicycleArea=assetCatalogList.value[0].bicycleArea:''
        // SKWYFSwitchType.value?listItem.CKWYF=assetCatalogList.value[0].CKWYF:''
        // bicyCostSwitchType.value?listItem.bicycleManagementCost=assetCatalogList.value[0].bicycleManagementCost:''
        timeRangeSwitchType.value?listItem.bicycleManagementStartDate=assetCatalogList.value[0].bicycleManagementStartDate:''
        timeRangeSwitchType.value?listItem.bicycleManagementEndDate=assetCatalogList.value[0].bicycleManagementEndDate:''
        isNeedInvoiceType.value?listItem.isNeedInvoice=assetCatalogList.value[0].isNeedInvoice:undefined
        listItem.projectId=assetCatalogList.value[0].projectId
        listItem.CKWYF=ckwyfValue.value
      }
    assetCatalogList.value.push(JSON.parse(JSON.stringify(listItem)))
}

const xmchanged = async (id,row)=> {
    xmOptions.value.forEach(element => {
      if(element.id == id) {
        row.projectName = element.projectName
        row.projectId = element.id
        assetCatalogList.value.forEach(item => {
          item.projectName = row.projectName
          item.projectId = row.projectId
        })
        /* if(xmswitchType.value) {
          assetCatalogList.value.forEach(item => {
            item.projectName = row.projectName
            item.projectId = row.projectId
          })
        } */
      }
    });
    // form.value.houseNumber = undefined
    queryParamsFW.value.projectId = id
    const res = await listHouseInfo(queryParamsFW.value);
    houseCostList.value = res.rows
    CKtotal.value = res.total
}

const countWYF = (value,row) => {
    if (value<=0) {
        ElMessage.warning('车库面积不能小于0')
    }
    row.bicycleManagementCost = Math.round(row.CKWYF * row.bicycleArea * 100) / 100
    /* if(ckAreaSwitchType.value && bicyCostSwitchType.value) {
        row.bicycleManagementCost = Math.round(row.CKWYF * row.bicycleArea * 100) / 100
        assetCatalogList.value.forEach(item => {
            item.bicycleArea = row.bicycleArea
            item.bicycleManagementCost = row.bicycleManagementCost
            // item.CKWYF = row.CKWYF
        })
    } else if(ckAreaSwitchType.value && !bicyCostSwitchType.value){
      assetCatalogList.value.forEach(item => {
        item.bicycleArea = row.bicycleArea
        item.bicycleManagementCost = Math.round(item.CKWYF * item.bicycleArea * 100) / 100
      })
    }else{
      row.bicycleManagementCost = Math.round(row.CKWYF * row.bicycleArea * 100) / 100
    } */
}

const changeBicyCost = (value,row) => {
    if (value<=0) {
        ElMessage.warning('车库物业费单价不能小于等于0')
    }
    row.bicycleManagementCost = Math.round(row.CKWYF * row.bicycleArea * 100) / 100
    /* if(SKWYFSwitchType.value) {
        assetCatalogList.value.forEach(item => {
            // item.bicycleArea = row.bicycleManagementCost
            // item.bicycleManagementCost = row.bicycleManagementCost
            item.CKWYF = row.CKWYF
        })
    } */
}

const countWYFDJ = (value,row) => {
    if (value<=0) {
        ElMessage.warning('车库物业费不能小于等于0')
    }
    row.CKWYF = row.bicycleArea != 0 ? row.CKWYF = Math.round(row.bicycleManagementCost/row.bicycleArea * 100) / 100 : row.CKWYF
    /* if(ckAreaSwitchType.value && bicyCostSwitchType.value) {
      row.CKWYF = row.bicycleArea != 0 ? row.CKWYF = Math.round(row.bicycleManagementCost/row.bicycleArea * 100) / 100 : row.CKWYF
      assetCatalogList.value.forEach(item => {
          item.bicycleArea = row.bicycleArea
          item.bicycleManagementCost = row.bicycleManagementCost
          item.CKWYF = row.CKWYF
      })
    } else if( !ckAreaSwitchType.value && bicyCostSwitchType.value){
        assetCatalogList.value.forEach(item => {
          item.bicycleManagementCost = row.bicycleManagementCost
          item.CKWYF = item.bicycleArea!= 0 ? Math.round(item.bicycleManagementCost/item.bicycleArea * 100) / 100 : item.CKWYF
        })
    } else {
      row.CKWYF = row.bicycleArea != 0 ? row.CKWYF = Math.round(row.bicycleManagementCost/row.bicycleArea * 100) / 100 : row.CKWYF
    } */
}

const startTimer = (value,row) => {
    row.bicycleManagementStartDate = value
    if (row.bicycleManagementStartDate) {
        let timer = addDays(row.bicycleManagementStartDate, 365)
        let date = new Date(timer);
        let y = date.getFullYear();
        let m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        let d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        row.bicycleManagementEndDate = y + '-' + m + '-' + d + ' 00:00:00'
    } else {
        row.bicycleManagementEndDate = undefined
    }
    if (timeRangeSwitchType.value) {
        assetCatalogList.value.forEach(item => {
            item.bicycleManagementStartDate = row.bicycleManagementStartDate
            item.bicycleManagementEndDate = row.bicycleManagementEndDate
        })
    }
}

const endTimer = (value,row) => {
    row.bicycleManagementEndDate = value
    if (row.bicycleManagementEndDate <= row.bicycleManagementStartDate) {
        startTimer(row.bicycleManagementStartDate,row)
        ElMessage.warning('结束时间不能小于开等于始时间');
    }
    if (timeRangeSwitchType.value) {
        assetCatalogList.value.forEach(item => {
            item.bicycleManagementStartDate = row.bicycleManagementStartDate
            item.bicycleManagementEndDate = row.bicycleManagementEndDate
        })
    }
}


const hasEmptyValue = (arr) => {
  let newArr = JSON.parse(JSON.stringify(arr))
  newArr = newArr.map(obj => {
    delete obj.bicyclePayDate;
    delete obj.bicyclePutDate;
    delete obj.remark;
    delete obj.CKWYF;
    return obj;
  });
  return !newArr.every(obj => Object.values(obj).every(value => value != null && value !== '' && value !== undefined));
}

const validateArray = (arr) =>{
  let falseList = []
  arr.forEach(function(item,index) {
    if (item.bicycleArea <= 0 || item.bicycleManagementCost <= 0) {
      let errObj = { errIndex:index }
      falseList.push(errObj)
    }
  });
  return falseList.length>0?true:false
}

const checkValueLenth = (arr) =>{
  let hasFalseList = []
  arr.forEach(function(item,index) {
    if (item.bicycleArea>99999999 || item.bicycleManagementCost>99999999) {
      hasFalseList.push(index)
    }
  });
  return hasFalseList.length>0?true:false
}

const hasDuplicateName = (arr) =>{
  return arr.some((item, index) => 
    arr.slice(0, index).some(otherItem => item.houseId === otherItem.houseId)
  );
}

const hasNoEmptyValues = () => {
    let flag = true
    let checkValue = hasEmptyValue(assetCatalogList.value)
    let hasLittleValue = validateArray(assetCatalogList.value)
    let checkLength = checkValueLenth(assetCatalogList.value)
    if(route.query.type == 'edit') {
      if (checkValue) {
          flag?ElMessage.error('请将信息填写完成！'):''
          flag = false
      } else if(hasLittleValue) {
          flag?ElMessage.error('车库面积或者车库物业费不能小于等于0!'):''
          flag = false
      } else if(checkLength) {
          flag?ElMessage.error('车库面积或者车库物业费数据不合理!'):''
          flag = false
      } else {
        flag = true
      }
    }else {
      if (checkValue) {
          flag?ElMessage.error('请将信息填写完成！'):''
          flag = false
      } else if(hasLittleValue) {
        flag?ElMessage.error('车库面积或者车库物业费不能小于等于0!'):''
        flag = false
      } else if(checkLength) {
        flag?ElMessage.error('车库面积或者车库物业费数据不合理!'):''
        flag = false
      } else {
        flag = true
      }
    }
    return flag
  }

const tableRowClassName = ({row,rowIndex,}: {row: any,rowIndex: number}) => {
  if (route.query.type == 'edit') return
  for (var i = 0; i < errRowIndexList.value.length; i++) {
    if (errRowIndexList.value[i].errIndex == rowIndex) {
      return 'warning-row'
    }
  }
  return ''
}
  
  // 提交全部
const handleQuery = async () => {
  // errRowIndexList.value = []
  if(hasNoEmptyValues()) {
    if(route.query.type == 'edit') {
        await updateBicycleCost({'bicycleCostListBo':assetCatalogList.value}).then(() =>  {proxy?.$modal.msgSuccess("修改成功");});
        await goBack()
    }else {
        await addBicycleCost({'bicycleCostListBo':assetCatalogList.value}).then(() =>  {proxy?.$modal.msgSuccess("新增成功");});
        await goBack()
    }
  }
}
  
  /** 返回 */
  const goBack = () =>{
    const obj = { path: "/costManagement/garageCost" };
    proxy?.$tab.closeOpenPage(obj);
  }

  const xmhandleVisibleChange = (visible: any) => {
    try {
      if (visible) {
        // 如果下拉框显示
        let xmDropdown: any = document.getElementsByClassName('xmDropdown')[0].parentElement.parentElement
        // 监听下拉框滚动事件
        xmDropdown.addEventListener('scroll', xmloadNextPage)
      } else {
        // 如果下拉框隐藏
        let xmDropdown: any = document.getElementsByClassName('xmDropdown')[0].parentElement.parentElement
        // 移除下拉框滚动事件监听
        xmDropdown.removeEventListener('scroll', xmloadNextPage)
      }
    } catch (error) {}
  }
  
  const xmloadNextPage = async () => {
    // let xmDropdown: any = document.querySelector('.el-select-dropdown__wrap');
    let xmDropdown: any = document.getElementsByClassName('xmDropdown')[0].parentElement.parentElement;
    // 判断下拉框是否触底
    if (xmDropdown.scrollTop + xmDropdown.clientHeight >= xmDropdown.scrollHeight - 2) {
      loadingmore.value = true
      if (xmOptions.value.length + 1 <= xmtotal.value && loadingmore.value) {
        xmqueryParams.value.pageNum ++
        const res = await listProject(xmqueryParams.value)
        xmOptions.value.length + 1 <= xmtotal.value?xmOptions.value.push(...res.rows):''
        loadingmore.value = false
        
      }else{
        loadingmore.value = false
        xmDropdown.removeEventListener('scroll', xmloadNextPage)
      }
    }
  }

  const househandleCkVisibleChange = (visible: any,scope:any) => {
    scopeCkHouseIndex.value = scope.$index
    try {
      if (visible) {
        // 如果下拉框显示
        let length = (document.getElementsByClassName('housCKAddDropdown').length)/assetCatalogList.value.length*scopeCkHouseIndex.value
        let housCKAddDropdown: any = document.getElementsByClassName('housCKAddDropdown')[length].parentElement.parentElement
        // 监听下拉框滚动事件
        housCKAddDropdown.addEventListener('scroll', houseCKLoadNextPage)
      } else {
        // 如果下拉框隐藏
        let length = (document.getElementsByClassName('housCKAddDropdown').length)/assetCatalogList.value.length*scopeCkHouseIndex.value
        let housCKAddDropdown: any = document.getElementsByClassName('housCKAddDropdown')[length].parentElement.parentElement
        // 移除下拉框滚动事件监听
        housCKAddDropdown.removeEventListener('scroll', houseCKLoadNextPage)
      }
    } catch (error) {}
  }
const houseCKLoadNextPage = async () => {
    let length = (document.getElementsByClassName('housCKAddDropdown').length)/assetCatalogList.value.length*scopeCkHouseIndex.value
    let housCKAddDropdown: any = document.getElementsByClassName('housCKAddDropdown')[length].parentElement.parentElement;
    // 判断下拉框是否触底
    if (housCKAddDropdown.scrollTop + housCKAddDropdown.clientHeight >= housCKAddDropdown.scrollHeight - 2) {
      loadingHouseMore.value = true
      if (houseCostList.value.length + 1 <= CKtotal.value && loadingHouseMore.value) {
        queryParamsFW.value.pageNum ++
        const res = await listHouseInfo(queryParamsFW.value)
        houseCostList.value.length + 1   <= CKtotal.value?houseCostList.value.push(...res.rows):''
        loadingHouseMore.value = false
      }else{
        loadingHouseMore.value = false
        housCKAddDropdown.removeEventListener('scroll', houseCKLoadNextPage)
      }
    }
  }

const getHouseHomeList = async (value: string) => {
  if (value) {
    queryParamsFW.value.houseNumber = value
    const house = await listHouseInfo(queryParamsFW.value);
    houseCostList.value = house.rows
    CKtotal.value = house.total
  }
}

const isNeedInvoiceChanged = (id:string,row:any) => {
  if(isNeedInvoiceType.value) {
    assetCatalogList.value.forEach(item => {
        item.isNeedInvoice = row.isNeedInvoice
      })
    }
}

  onMounted(async () => {
    await getList()
    route.query.type == 'edit' ? sessionStorage.setItem("searchFlag", '0') : sessionStorage.setItem("searchFlag", '1')
    if(route.query.type == 'edit') {
        const res = await getBicycleCost(route.query.bicycleCostId);
        assetCatalogList.value = [res.data]
        assetCatalogList.value.forEach( element => {
          element.CKWYF = Math.round(element.bicycleManagementCost/element.bicycleArea * 100) / 100
        })
    }else{
      addLine()
    }
  })
  </script>
  <style>
  .addListBox .el-date-editor  {
    --el-date-editor-width: 122px;
  }
  .error-row {
  background-color: #ffdddd; /* 浅红色背景 */
}
.error-message {
  color: #ff0000; /* 红色文字 */
  font-size: 12px;
  margin-top: 5px;
}
  </style>
  <style>
  .el-table .warning-row {
    --el-table-tr-bg-color: var(--el-color-danger-light-3);
  }
  </style>
  